package cn.itcast.advance.c2;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
public class RedisClient {
    private static final String BLANK = " ";
    /*
    set name zhangsan
    *3
    $3
    set
    $4
    name
    $8
    zhangsan
     */
    public static void main(String[] args) {
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            AtomicBoolean EXIT = new AtomicBoolean(false);
            Scanner scanner = new Scanner(System.in);
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.group(worker);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) {
                    ch.pipeline().addLast(new LoggingHandler());
                    ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                        @Override
                        public void channelActive(ChannelHandlerContext ctx) {
                           new Thread(() -> {
                               while (true){
                                   if (EXIT.get()) {
                                       log.debug("您已退出..");
                                       return;
                                   }
                                   //获取输入
                                   String command = scanner.nextLine();
                                   if ("exit".equals(command)) {
                                       ctx.channel().close();
                                   }
                                   //发送命令
                                   sendMessage(command,ctx);
                               }
                           },"command-thread").start();
                        }

                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) {
                            ByteBuf buf = (ByteBuf) msg;
                            System.out.println(buf.toString(Charset.defaultCharset()));
                        }
                        // 在连接断开时触发
                        @Override
                        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                            log.debug("连接已经断开，按任意键退出..");
                            EXIT.set(true);
                        }

                        // 在出现异常时触发
                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                            log.debug("连接已经断开，按任意键退出..{}", cause.getMessage());
                            EXIT.set(true);
                        }
                    });
                }
            });
            ChannelFuture channelFuture = bootstrap.connect("localhost", 6379).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("client error", e);
        } finally {
            worker.shutdownGracefully();
        }
    }


    private static void sendMessage(String command, ChannelHandlerContext ctx) {
        final byte[] LINE = {13, 10}; // \r\n
        ByteBuf buf = ctx.alloc().buffer();
        String[] commandArray = command.split(BLANK);
        String commandNum= "*"+commandArray.length;
        buf.writeBytes(commandNum.getBytes());
        buf.writeBytes(LINE);
        for (String comm : commandArray) {
            //$3
            String commandLen = "$"+comm.length();
            buf.writeBytes(commandLen.getBytes());
            buf.writeBytes(LINE);
            //set
            buf.writeBytes(comm.getBytes());
            buf.writeBytes(LINE);
        }
        ctx.writeAndFlush(buf);
    }


}
